'use strict';

const fs = require('fs');//文件处理模块，分为同步和异步调用
const path = require('path');//js中路径处理模块

exports.getCurrentDate = () => {
	var date = new Date();
    date.getYear();
    date.getFullYear();
    date.getMonth();
    date.getDate();
    date.getDay();
    date.getTime();
    date.getHours();
    date.getMinutes();
    date.getSeconds();
    var d=date.toLocaleString();
	return d;
};

exports.buildCCPOrg1 = () => {
	const ccpPath = path.resolve(__dirname, '..', 'organizations', 'peerOrganizations', 'org1.project.com', 'connection-org1.json');
	const fileExists = fs.existsSync(ccpPath);
	if (!fileExists) {
		throw new Error(`no such file or directory: ${ccpPath}`);
	}
	const contents = fs.readFileSync(ccpPath, 'utf8');
	const ccp = JSON.parse(contents);

	console.log(`Loaded the network configuration located at ${ccpPath}`);
	return ccp;//返回一个object，此object即为连接对象
};

exports.buildCCPOrg2 = () => {
	const ccpPath = path.resolve(__dirname, '..', 'organizations', 'peerOrganizations', 'org2.project.com', 'connection-org2.json');
	const fileExists = fs.existsSync(ccpPath);
	if (!fileExists) {
		throw new Error(`no such file or directory: ${ccpPath}`);
	}
	const contents = fs.readFileSync(ccpPath, 'utf8');
	const ccp = JSON.parse(contents);

	console.log(`Loaded the network configuration located at ${ccpPath}`);
	return ccp;
};

exports.buildCCPOrg3 = () => {
	const ccpPath = path.resolve(__dirname, '..', 'organizations', 'peerOrganizations', 'org3.project.com', 'connection-org3.json');
	const fileExists = fs.existsSync(ccpPath);
	if (!fileExists) {
		throw new Error(`no such file or directory: ${ccpPath}`);
	}
	const contents = fs.readFileSync(ccpPath, 'utf8');
	const ccp = JSON.parse(contents);

	console.log(`Loaded the network configuration located at ${ccpPath}`);
	return ccp;
};

exports.buildWallet = async (Wallets, walletPath) => {
	//创建钱包用于管理身份
	let wallet;
	if (walletPath) {
		wallet = await Wallets.newFileSystemWallet(walletPath);
		console.log(`Built a file system wallet at ${walletPath}`);
	} else {
		wallet = await Wallets.newInMemoryWallet();
		console.log('Built an in memory wallet');
	}

	return wallet;
};

exports.prettyJSONString = (inputString) => {
	//此函数用于将json对象以较为美观的字符串的形式输出
	if (inputString) {
		return JSON.stringify(JSON.parse(inputString), null, 2);
	}
	else {
		return inputString;
	}
}
